import 'dart:convert';

import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/http/api_type.dart';
import 'package:inmotion_pro/pages/models/account_model_3rd.dart';
import 'package:inmotion_pro/pages/models/http_response/http_response_model.dart';
import 'package:inmotion_pro/pages/models/http_response/user_info_response_model.dart';
import 'package:inmotion_pro/pages/models/user_model.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import '../custom_exception/api_exception.dart';

// 账号相关的API扩展
extension ApiHelperAccountExtension on ApiHelper {
  // MARK: - 发送证码
  Future<(bool, String)> requestVerificationCode({
    required String account,
    required CodePlatform platform,
    required CodeType codeType,
    String? securityToken,
    Map<String, String>? tokenMap,
  }) {
    return httpManager.request<HttpResponseModel>(
      RequestType.POST,
      "/v1/user/v-code/request",
      HttpResponseModel.fromJson,
      data: {
        "target": account,
        "type": platform == CodePlatform.email ? 'email' : 'sms',
        "biz": codeType.val,
        if (securityToken != null) "security_token": securityToken,
        if (tokenMap != null) ...tokenMap,
      },
    ).then((response) {
      if (response.isSuccess) {
        // 验证码验证成功
        return (true, "");
      } else if (response.code == ApiErrorType.verifyCaptcha.code &&
          response.data != null) {
        // 验证码验证失败，回传图形验证码URL
        return (false, response.data!.captchaUrl);
      }
      throw ApiException(response.code, response.message);
    });
  }

  // MARK: - 校验验证码
  Future<String> verifyVerificationCode({
    required String account,
    required CodePlatform platform,
    required CodeType codeType,
    required String code,
  }) {
    return httpManager.request<HttpResponseModel>(
      RequestType.POST,
      "/v1/user/v-code/verify",
      HttpResponseModel.fromJson,
      data: {
        "target": account,
        "type": platform == CodePlatform.email ? 'email' : 'sms',
        "biz": codeType.val,
        "code": code,
      },
    ).then((response) {
      if (!response.isSuccess || response.data == null) {
        throw ApiException(response.code, response.message);
      }
      return response.data!.verifyToken;
    });
  }

  // MARK: - 邮箱注册
  Future<UserModel> emailRegister({
    required String email,
    required String password,
    required String verifyToken,
  }) {
    return httpManager.request<UserInfoResponseModel>(
      RequestType.POST,
      "/v1/user/register",
      UserInfoResponseModel.fromJson,
      data: {
        "timezone_offset": DateTime.now().timeZoneOffset.inHours,
        "email": email,
        "password": password,
        "token": verifyToken,
      },
    ).then((response) {
      if (!response.isSuccess || response.data == null) {
        throw ApiException(response.code, response.message);
      }
      return response.data!.user;
    });
  }

  // MARK: - 登录
  Future<UserModel> login({
    String? name,
    String? email,
    String? phone,
    String? password,
    String? code,
    String? oneKeyVerifyPhoneToken,
    Auth3rdModel? auth3rdModel,
  }) {
    return httpManager.request<UserInfoResponseModel>(
      RequestType.POST,
      "/v1/user/login",
      UserInfoResponseModel.fromJson,
      data: {
        "timezone_offset": DateTime.now().timeZoneOffset.inHours,
        if (name != null) "name": name,
        if (email != null) "email": email,
        if (phone != null) "phone": phone,
        if (oneKeyVerifyPhoneToken != null)
          "one_key_verify_phone_token": oneKeyVerifyPhoneToken,
        if (password != null) "password": password,
        if (code != null) 'code': code,
        if (auth3rdModel != null && auth3rdModel.auth3rdType != null)
          "${auth3rdModel.auth3rdType?.name}_elite":
              jsonEncode(auth3rdModel.toMap()),
      },
    ).then((response) {
      if (!response.isSuccess || response.data == null) {
        throw ApiException(response.code, response.message);
      }
      return response.data!.user;
    });
  }

  // MARK: - 退出登录
  Future<bool> logout(String refreshToken) {
    return httpManager.request<HttpResponseModel>(
      RequestType.POST,
      "/v1/user/logout",
      HttpResponseModel.fromJson,
      data: {
        "refresh_token": refreshToken,
      },
    ).then((response) {
      if (!response.isSuccess) {
        throw ApiException(response.code, response.message);
      }
      return response.isSuccess;
    });
  }

  // MARK: - 账号注销
  Future<bool> removeAccount() {
    return httpManager
        .request<HttpResponseModel>(
      RequestType.POST,
      "/v1/user/delete-account/apply",
      HttpResponseModel.fromJson,
    )
        .then((rsp) {
      if (!rsp.isSuccess) {
        throw ApiException(rsp.code, rsp.message);
      }
      return rsp.isSuccess;
    });
  }

  // MARK: - 获取用户信息
  Future<UserModel> getUserInfo() {
    return httpManager
        .request<HttpResponseModel>(
            RequestType.GET, "/v1/user/info", HttpResponseModel.fromJson)
        .then((response) {
      if (!response.isSuccess || response.data == null) {
        throw ApiException(response.code, response.message);
      }
      return UserModel.fromMap(response.data!.originData);
    });
  }

  // MARK: - 修改用户信息
  Future<bool> updateUserInfo({
    String? nickname,
    String? avatar,
    String? country,
    String? province,
    String? signature,
  }) {
    return httpManager.request<HttpResponseModel>(
      RequestType.POST,
      "/v1/user/info",
      HttpResponseModel.fromJson,
      data: {
        if (nickname != null) "nickname": nickname,
        if (avatar != null) "avatar": avatar,
        if (country != null) "country": country,
        if (province != null) "province": province,
        if (signature != null) "signature": signature,
      },
    ).then((response) {
      if (!response.isSuccess) {
        throw ApiException(response.code, response.message);
      }
      return response.isSuccess;
    });
  }

  // MARK: - 忘记密码 / 重置密码
  Future<bool> resetPassword({
    required String email,
    required String password,
    String? securityToken, // 当登录状态下修改密码时，需要传token
  }) {
    return httpManager.request<HttpResponseModel>(
      RequestType.POST,
      "/v1/user/password/reset",
      HttpResponseModel.fromJson,
      data: {
        "timezone_offset": DateTime.now().timeZoneOffset.inHours,
        "email": email,
        "password": password,
        if (securityToken != null) "token": securityToken,
      },
    ).then((response) {
      if (!response.isSuccess) {
        throw ApiException(response.code, response.message);
      }
      return response.isSuccess;
    });
  }

  // MARK: - 获取第三方账号绑定列表
  Future<List<AccountModel3rd>> get3rdAuthBindingList() {
    return httpManager.request<AccountModel3rd>(
      RequestType.GET,
      "/v1/user/social-account/all",
      AccountModel3rd.fromJson,
      queryParameters: {
        ...baseGetMap(),
      },
    ).then((response) {
      if (!response.isSuccess || response.listData == null) {
        throw ApiException(response.code, response.message);
      }
      return response.listData!;
    });
  }

  // MARK: - 绑定第三方账号
  Future<bool> bind3rdAuthAccount(String platformToken, String platform) {
    return httpManager.request<HttpResponseModel>(
      RequestType.POST,
      "/v1/user/social-account/bind",
      HttpResponseModel.fromJson,
      data: {
        "platformToken": platformToken,
        "platform": "${platform}_elite",
      },
    ).then((response) {
      if (!response.isSuccess) {
        throw ApiException(response.code, response.message);
      }
      return response.isSuccess;
    });
  }

  // MARK: - 解绑第三方账号
  Future<bool> unbind3rdAuthAccount(String platform) {
    return httpManager.request<HttpResponseModel>(
      RequestType.POST,
      "/v1/user/social-account/unbind",
      HttpResponseModel.fromJson,
      data: {
        "platform": "${platform}_elite",
      },
    ).then((response) {
      if (!response.isSuccess) {
        throw ApiException(response.code, response.message);
      }
      return response.isSuccess;
    });
  }

  // MARK: - 绑定手机号
  Future<bool> bindPhoneNumber({
    required String phone,
    required String verifyToken, // 新绑定的手机号的验证码token
    required String securityToken, // 旧手机号/邮箱检验完成后的安全操作token
  }) {
    return httpManager.request<HttpResponseModel>(
      RequestType.POST,
      "/v1/user/bind-phone",
      HttpResponseModel.fromJson,
      data: {
        "phone": phone,
        "phone_token": verifyToken,
        "previous_token": securityToken,
      },
    ).then((response) {
      if (!response.isSuccess) {
        throw ApiException(response.code, response.message);
      }
      return response.isSuccess;
    });
  }

  // MARK: - 绑定邮箱
  Future<bool> bindEmail({
    required String email,
    required String verifyToken,
    required String securityToken,
  }) {
    return httpManager.request<HttpResponseModel>(
      RequestType.POST,
      "/v1/user/bind-email",
      HttpResponseModel.fromJson,
      data: {
        "email": email,
        "email_token": verifyToken,
        "previous_token": securityToken,
      },
    ).then((response) {
      if (!response.isSuccess) {
        throw ApiException(response.code, response.message);
      }
      return response.isSuccess;
    });
  }
}
